package org.micode.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Slf4j
public class Base64Utils {

    private static final Base64.Decoder decoder = Base64.getDecoder();

    private static final Base64.Encoder encoder= Base64.getEncoder();

    /**
     * 解码
     * @param str
     * @return
     */
    public static String decode(String str){
        return decode(str, "UTF-8");
    }

    /**
     * 解码
     * @param str
     * @return
     */
    public static byte[] decodeByte(String str){
        return decodeByte(str, StandardCharsets.UTF_8.name());
    }

    public static byte[] decodeByte(String str, String charsetName){
        try {
            return decoder.decode(str.getBytes(charsetName));
        } catch (Exception e) {
            log.error("解码失败", e);
            return null;
        }
    }

    public static String decode(String str, String charsetName){
        byte[] bytes = null;
        try {
            bytes = decoder.decode(str.getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            log.error("Decode failed", e);
            return null;
        }
        try {
            return new String(bytes, charsetName);
        } catch (UnsupportedEncodingException e) {
            log.error("Decode failed", e);
            return null;
        }
    }

    /**
     * 编码
     * @param str
     * @return
     */
    public static String encode(String str){
        return encoder.encodeToString(str.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * byte[]转base64
     *
     * @param b
     * @return
     */
    public static String byte2Base64StringFun(byte[] b){
        return encoder.encodeToString(b);
    }

}
